//
//  AIGirlModelDetailViewController.swift
//  AIGirl
//
//  Created by Rae on 2023/12/29.
//

import UIKit
import JXBanner
import JXPageControl
import SnapKit

class AIGirlModelDetailViewController: AIGirlBaseViewController {
    
    private var navView = AIGirlModelDetailNavView()
    private var bottomView = AIGirlModelDetailBottomView()
    private lazy var linearBanner: JXBanner = {[weak self] in
        let banner = JXBanner()
//        banner.placeholderImgView.image = UIImage(named: "FJ_Common_placeholder")
        banner.indentify = "linearBanner"
        banner.delegate = self
        banner.dataSource = self
        return banner
    }()
    //是否弹出购买挽留
    private var isShow = false
    private var photoDtos = [AIGirlDiscoverDetailPicModel]()
    var updateDataClosure: (() -> Void)?
    
    var model: AIGirlItemModel?{
        didSet{
            guard let md = model else { return }
            navView.isVip = md.isVip == 1
//            bottomView.isVip = md.isVip == 1
            bottomView.model = md
            loadData(girlId: md.modelId)
        }
    }
    
    private func loadData(girlId: Int) {
        
        request.start(.girlDetailInfo(girlId: girlId), type: AIGirlDiscoverDetailModel.self) { result in
            
            if result.isSuccessful, let model = result.model {
                self.photoDtos = model.photoDtos
                self.navView.picTotal = model.photoDtos.count
                self.navView.currentIndex = 1
                self.bottomView.detailModel = model
                self.linearBanner.reloadView()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .black
        view.subviews {
            linearBanner
            navView
            bottomView
        }
        isShow = false
        linearBanner.fillContainer()
        navView.leading(0).trailing(0).top(.statusHeight).height(50.0)
        bottomView.leading(0).trailing(0).bottom(0).height(130.0)
        
        navView.backClosure = {
            self.clickBackButton()
        }
        bottomView.likeClosure = { [weak self] isLike in
            self?.request.start(.collectGirl(girlId: self?.model?.modelId ?? 0), completion: { result in
                if result.isSuccessful {
                    self?.updateDataClosure?()
                    "Success!".toast_success
                }
            })
        }
        bottomView.getClosure = { [weak self] model in
            self?.request.start(.unlockMessage(id: model.modelId, type: 0), completion: { result in
                if result.isSuccessful {
                    GlobalTool.refreshUserInfo()
                    NotificationCenter.default.post(name: NSNotification.Name("refreshGirls"), object: nil)
                    
                    let bugView = AIGirlBuySuccessView()
                    bugView.model = model
                    bugView.setBgClosure = { girlId, photoId in
                        self?.request.start(.saveChatBackground(girlId: girlId, photoId: photoId), completion: { res in
                            if res.isSuccessful {
                                "Success!".toast_success
                                self?.updateDataClosure?()
                                self?.navigationController?.popViewController(animated: true)
                            }
                        })
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
                        self?.animation.animation(show: bugView)
                    }
                }else {
                    if result.errorCode == 20007 { //报错 20007 也需要vip
                        GlobalTool.showVipInfoPage(dismissClosure: {
                            if self?.isShow ?? false == false {
                                let detainV = AIGirlDetainmentView()
                                detainV.purchaseClosure = {
                                    GlobalTool.showVipInfoPage()
                                }
                                self?.animation.animation(show: detainV)
                            }
                            self?.isShow = true
                        }, buyUpdateClosure: nil)
                    }
                }
            })
        }
        bottomView.vipClosure = {
            GlobalTool.showVipInfoPage(dismissClosure: {
                if !self.isShow {
                    let detainV = AIGirlDetainmentView()
                    detainV.purchaseClosure = {
                        GlobalTool.showVipInfoPage()
                    }
                    self.animation.animation(show: detainV)
                }
                self.isShow = true
            }, buyUpdateClosure: nil)
        }
        bottomView.bugCoinClosure = {
            let coinV = AIGirlMessagePremiumView()
            if !self.isShow {
                coinV.dismissClosure = {
                    let detainV = AIGirlDetainmentView()
                    detainV.purchaseClosure = {
                        self.animation.animation(show: AIGirlMessagePremiumView())
                    }
                    self.animation.animation(show: detainV)
                }
            }            
            self.isShow = true
            self.animation.animation(show: coinV)
        }
    }

    private func setChatBackground(){
        
//        saveChatBackground
    }
}

extension AIGirlModelDetailViewController: JXBannerDataSource, JXBannerDelegate {
    
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return photoDtos.count
    }

    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {

        return JXBannerCellRegister(type: AIGirlModelDetailCell.self,
                                        reuseIdentifier: "FJBannerCell")
    }

    func jxBanner(_ banner: JXBannerType,
                  cellForItemAt index: Int,
                  cell: UICollectionViewCell) -> UICollectionViewCell {

        guard let imageCell = cell as? AIGirlModelDetailCell else {
            return cell
        }
        imageCell.backgroundColor = .black
        
        imageCell.model = photoDtos[index]
        return imageCell
    }

    func jxBanner(_ banner: JXBannerType,
                  params: JXBannerParams) -> JXBannerParams {

        return params
            .timeInterval(2)
            .cycleWay(.forward)
            .isAutoPlay(false)
    }
    
    // 最中心显示cell 索引
    func jxBanner(_ banner: JXBannerType, center index: Int) {
//        if photoDtos.count > index {
//            self.bottomView.model = photoDtos[index]
//        }
        if photoDtos.count > index {
            let model = photoDtos[index]
//            bottomView.picModel = model
           
        }
        self.navView.currentIndex = index + 1
    }
}


class AIGirlModelDetailCell: JXBannerBaseCell {

    private lazy var bannarImg = c_make_ex(UIImageView.self).mode(.scaleAspectFill).end()

    var model: AIGirlDiscoverDetailPicModel?{
        didSet{
            guard let md = model else { return }
            let orUrl = md.image
            let realUrl = String(orUrl.filter { $0 != "\t" })
            bannarImg.loadImage(url: realUrl)
        }
    }
    
    open override func jx_addSubviews() {
        super.jx_addSubviews()
        contentView.subviews{
            bannarImg
        }

        bannarImg.fillContainer()
        bannarImg.clipsToBounds = true
        bannarImg.contentMode = .scaleAspectFit
    }
}
